import uvicorn

from fastapi import FastAPI, Body
from pydantic import BaseModel
from matcher import PsychologyMatcher
from model_loader import load_embedding_model
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI(title="匹配接口")

# 增加跨域能力 方便测试
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 或者写局域网内允许的地址列表
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 加载模型与数据
model = load_embedding_model()
matcher = PsychologyMatcher(model, "data_infos/class_data.xlsx")

class MatchRequest(BaseModel):
    text: str

@app.post("/match/", summary="两阶段匹配接口")
def match_psychological_issue(req: MatchRequest):
    # 阶段一：匹配类别
    match_datas = matcher.match_category(req.text)

    # 阶段二：匹配心理问题
    all_return = []
    for match_data in match_datas:
        category, score1 = match_data[0], match_data[1]
        result = matcher.match_issue_in_category(category, req.text)
        all_return.append({"类别": category, "心理问题匹配结果": result})

    return all_return

uvicorn.run(app, host="192.168.1.101", port=8080)
# uvicorn.run(app, host="172.20.0.89", port=8080)